package com.heima.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

import com.heima.common.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class Tokeninterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info(token);
        if (!StringUtils.hasText(token)){
            log.info("zhe被拦截");
            throw new RuntimeException("拦截了");
        }
        boolean verify = JWTUtil.verify(token, "code".getBytes());
        if (!verify){
            return false;
        }
        JWT jwt = JWTUtil.parseToken(token);
        Object id = jwt.getPayload("id");
        System.out.println(id);
        UserThreadLocal.set((Integer) id);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
